﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;

namespace com.sharepointutils.application
{
    public class QueryBuilder
    {
        public String Scope { get; set; }
        public int RowLimit { get; set; }
        public String RowLimitXML() { return "<RowLimit>" + this.RowLimit + "</RowLimit>"; }
        public List<QueryFieldRef> ViewFields = new List<QueryFieldRef>();
        public QueryCondition Condition { get; set; }

        public String ViewFieldsXML()
        {
            StringBuilder xml = new StringBuilder();

            foreach (QueryFieldRef field in this.ViewFields)
            {
                xml.Append(field.ToString());
            }

            return xml.ToString();
        }

        public QueryBuilder()
        {
            this.Scope = "RecursiveAll";
        }

        public QueryBuilder(String xml)
        {
            //TODO parse xml to properties
        }

        public String toClientQueryXML()
        {
            StringBuilder xml = new StringBuilder();


            xml.AppendFormat("<View Scope=\"{0}\" ><Query><Where>", this.Scope);
            xml.Append(this.Condition);
            xml.Append(this.RowLimitXML());
            xml.Append("</Where></Query></View>");

            return xml.ToString();
        }

        public CamlQuery toCamlQuery()
        {
            CamlQuery q = new CamlQuery();
            q.ViewXml = this.toClientQueryXML();
            return q;
        }

        public void where()
        {


        }

        public void orderBy()
        {


        }

        public void first()
        {


        }

        public void last()
        {


        }

        public void distinct()
        {


        }

        public void select(String[] fieldNames)
        {
            foreach (String s in fieldNames)
            {
                this.ViewFields.Add(new QueryFieldRef(s));
            }
        }
    }
}
